package controllers

import config.Search
import javax.inject.{Inject, Singleton}
import play.api.data.Form
import play.api.data.Forms._
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}
import utils.TableUtils
import utils.TableUtils._

import scala.concurrent.ExecutionContext

@Singleton
class SearchController @Inject()(cc: ControllerComponents)
                                (implicit exec: ExecutionContext) extends AbstractController(cc) {


  def searchBefore(db:String,input:String) = Action{implicit request=>
    Ok(views.html.english.search.search(db,input))
  }

  case class searchData(db: String, input: String)

  val searchForm = Form(
    mapping(
      "db" -> text,
      "input" -> text
    )(searchData.apply)(searchData.unapply)
  )


  def searchByDbInput(db:String,input:String) = Action { implicit request =>
    val page = pageForm.bindFromRequest.get
    val option = Array( "Name","Phylum", "Class", "Order", "Family", "Genus", "Species","Collection places",
      "Configuration", "Submiter", "Journal","Title","Authors","Collection Info","Collection Date")

    if(Search.searchMap.getOrElse(input,"") == ""){
      Search.getSearchMap(input)
    }

    Search.searchTimeMap.put(input, System.currentTimeMillis())

    val result = db match {
      case "all" => Search.searchMap(input)
      case "cp" => Search.searchMap(input).filter(_._1=="cp")
      case "mt" => Search.searchMap(input).filter(_._1=="mt")
    }

    val total = result.size
    val tmpX = result.slice(page.offset, page.offset + page.limit)

    val keys = input.trim.split(" ").map(_.trim)
    val row = tmpX.map{x=>
      val (r,species) = x._1 match {
        case "cp" => (TableUtils.cpSearch.find(_._1 == x._2).get,"Chloroplast")
        case  "mt" =>  (TableUtils.mtSearch.find(_._1 == x._2).get,"Mitochondria")
     }
      val text = r._3.split("\t")
      val result = keys.map{k=>
        val results= text.zipWithIndex.find(_._1.indexOf(k) != -1).get
       Json.obj("option" -> option(results._2),"result" -> Search.getKeyWord(results._1,input))
      }.distinct
      Json.obj("id" -> r._1, "geneid" -> text.head, "species" -> species,  "result" -> result)
    }

    Ok(Json.obj("rows" -> row, "total" -> total))
  }



}
